# coding: utf-8

'''
http://wiki.it.yzs.io:8090/pages/viewpage.action?pageId=27905992
'''

import sys
import time
import json
import hashlib
import urllib2
import requests

from utils.req import *

reload(sys)
sys.setdefaultencoding('utf8')

def get_secret(appkey):
    app_sec_map = {
        "vihbue6kvclagieoslsrnvdrprqtj6adqmxcvmai": "f88d891912d7c6a89d42bcba9456882a",
        "n4hafcui4asitycykk3tdodhj3uxfdzxx26ij6qf" : "11f65d3bb838613a6992c16550a355d4"
        }
    return app_sec_map[appkey]

def build_signature(params_dict):
    sign_keys = (
                'appkey', 'method', 'ver', 'udid', 
                'gps', 'appver', 'text', 'history', 
                'city', 'time', 'voiceid', 'scenario', 
                'screen', 'dpi', 'platform', 'viewid')

    secret = ''
    for k in params_dict.keys():
        if k.lower() == 'appkey':
            secret = get_secret(params_dict['appkey'])
    point_keys = []
    for key in params_dict.keys():
        if key.lower() in sign_keys:
            point_keys.append(key)
    sorted_point_keys = sorted(point_keys)
    s = secret + '&'
    for i in sorted_point_keys:
        s += "%s=%s" % (i, params_dict[i])
        s += '&'
    s += secret
    signature = hashlib.sha1(s.encode('utf-8')).hexdigest().upper().strip()
    return signature

def current_time():
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

def skill_service(skill_id, text, udid, skill_version='0'):
    ''' 单技能访问接口区别于公有云 '''
    url = 'http://%s/%s/skillservice' % (Server, Project)
    params = {
        'text' : text, # no url encode
        'udid' : udid,
        'skillId' : skill_id,
        'version' : skill_version,
    }
    # skillservice POST, URL Encoding
    return send_post(url, params)

def nlu_service(appkey, text, udid):
    # url = 'http://%s/%s/nluservice' % (Server, Project)
    url = 'http://%s/%s/iss' % (Server, Project)

    params = {
        'appkey' : appkey,
        'udid' : udid,
        'text' : text,
        # 'text' : urllib2.quote(text),
        'time' : current_time(),
        'method' : 'iss.getTalk',
        'ver' : '3.2',
        'voiceid' : 'no-voiceid-4-this-request',
        'appver' : 'v1.0.1',
        'scenario' : '',
    }
    params['appsig'] = build_signature(params)
    # nluservice GET, URL Encoding
    return send_get(url, params)


def get_current_audio_inf():
    url = 'http://%s/%s/iss' % (Server, Project)

    params = {
        'appkey' : appkey,
        'udid' : udid,
    }
    params['appsig'] = build_signature(params)
    # nluservice GET, URL Encoding
    return send_get(url, params)

def send_event():
    event = '''{
        "type": "AudioPlayer.LastFinished",
        "token": "token_test_from_python",
        "widgetToken": "widgetToken_test_from_python",
        "offsetInMilliseconds": 25000,
        "code": "no-code",
        "msg": "no-msg"
    }'''

    params = {
        "appkey": AppKey,
        "udid": UDID,
        "eventReportParams": event
    }
    # headers = {}
    # url = "%s/event/report?&=%s&eventReportParams=%s" % (Server, AppKey, '', eventReportParams)
    server = "http://usk-event-bj.hivoice.cn"
    url = "%s/event/report" % server
    print send_get(url, params)

def perf_test():
    tid = '0'
    log = 'log.log'
    duration = 10

    if len(sys.argv) >= 3:
        tid = sys.argv[1]
        duration = int(sys.argv[2])
    if len(sys.argv) >= 4:
        log = sys.argv[3]

    pass_ = 0
    total = 0
    text = '北京今天天气'
    print "thread %s will run %s(s)" % (tid, duration)
    begin = time.time()
    while time.time() < begin + duration:
        # ret = nlu_service(AppKey, UDID, text)
        ret = skill_service(text, UDID, Skill_Id, Skill_Version)
        if '"rc":0' in ret:
            pass_ += 1
        total += 1

    dur = (time.time() - begin)
    tps = pass_ / dur
    reps_time = dur / pass_
    result = '\nthread: %s: total: %d, pass_: %d, TPS: %.2f, reps_time: %.4f, elapsed_time: %.2f\n' %(tid, total, pass_, tps, reps_time, dur)
    print result.strip()
    with open(log, 'a') as log:
        log.write(result)


if __name__ == '__main__':
    Project = 'nlu-manage' # tomcat webapps 下的路径名
    # ENV = "UAT"
    ENV = "OL"

    # UAT Testing
    Server = '172.18.10.69:8080' # UAT
    AppKey = "vihbue6kvclagieoslsrnvdrprqtj6adqmxcvmai"
    Skill_Id = "2e09f5b99d26424b8e5bb5561bbc9342"   # UAT 技能自动化
    

    if ENV != "UAT": # Online Testing
        AppKey = "n4hafcui4asitycykk3tdodhj3uxfdzxx26ij6qf" # 技能自动化Appkey
        Skill_Id = '7323fb200c3141d5b956903e48b5a1e6' # 技能自动化

        # Server = '172.20.71.22:8080' # Online-BJ
        # Server = '172.20.61.217:8080' # Online-BJ
        Server = '172.20.7.201:8080' # BJ SLB
        
        # Server = '172.30.5.32:8080' # SH Online SLB
        # Server = '172.30.51.190:8080' # SH
        # Server = '172.30.41.249:8080' # SH
        
        # 上海 NLU custom data 节点:
        # Server = '172.30.5.33:8080' # SH Online SLB
        # data_processor = '172.30.41.248'
        # data_processor = '172.30.51.189'

    Skill_Version = '0'
    UDID = 'dakang-test-nlu-manager-0000'

    # text = '中国石油股票'
    # text = '白羊座今天运势'
    # text = '狮子的百科'
    # text = '北京限行'
    # text = "香蕉皮是什么垃圾"
    text = "来首忘情水"
    
    nlu_service(AppKey, text, UDID)
    skill_service(Skill_Id, text, UDID, Skill_Version)
    get_current_audio_inf()

    # 事件上报
    # text = "我想听周杰伦的歌"
    # nlu_service(AppKey, text, UDID)
    # send_event()
    # perf_test()
